#include "Tcp_Connection.hpp"
#include "Message.hpp"


enum Connectiontype{
	Client = 0 ,
	Sensor,
	Unknown

};

class Connection_End : public Tcp_Connection
{

 Connectiontype m_Entity;
 int m_CnnectionID;

public:
	typedef boost::shared_ptr<Connection_End> ConnectionEndPointer;
	
	Connection_End(boost::asio::io_service& io_service , int connectionID ): Tcp_Connection( io_service )
	{

		m_CnnectionID = connectionID;
		std::cout<<"Instantiating a new instance of Connection_end with ID"<< m_CnnectionID <<std::endl;
		m_Entity == Unknown;
	}
	
	void Recv_Handler(  const boost::system::error_code& error, // Result of operation.
						std::size_t bytes_transferred           // Number of bytes received.
					)
	{
		std::cout<<"In receive handler\n";

		if( !error )
			{
				std::cout<<"ConnecionEnd::Recv_Handler \n";
				std::cout<<"Received: "<<bytes_transferred<<"Bytes !"<<std::endl;
				Message ReceievedMessage;
				std::string MsgBuf = buf;
				std::cout<<"ConnectionEnd::RecvHandler:MsgBuf.length()= "<<MsgBuf.length()<<std::endl;


				if( ReceievedMessage.Decode( MsgBuf ) )
				{
						std::cout<<"Message is"<<MsgBuf<<" Length is: "<<MsgBuf.length()<<std::endl;
//						if(		ReceievedMessage.m_action == ENTITY &&
//								ReceievedMessage.data == "Client" )
//						{
							m_Entity == Client;
							SendAck( ReceievedMessage );
//						}
				}
				else
				{
					std::cout<<"Error, Message decode failed";
				}
				Receieve();
			}
			else
			{
				std::cerr<<"Error, closing connection with ID"<<m_CnnectionID<<std::endl;
				socket_.cancel();
				socket_.close();
			}

	}



virtual	tcp::socket& socket()
	{
		std::cout<<"Returning Socket for connection ID: "<<m_CnnectionID<<std::endl;
		return socket_;
	}

	bool Handle_Send( const boost::system::error_code& error, size_t bytes_transferred )
	{
		std::cout<<"Connection_End class"<<std::endl;
		std::cout<<"Sent "<<bytes_transferred<<" Bytes on Socket "<<std::endl;
		return true;
	}


	bool PushData( Message m )
	{
		return true;
	};


	///
	//Receives a message and sends an Ack for that message.
	//
	bool SendAck( Message Msg )
	{

		Msg.m_MsgType = ACK ;
		std::string AckMsg = Msg.Encode();
		Send( AckMsg );
		std::cout<<"sent an acknowledgment message"<<AckMsg<<"."<<std::endl;
		return true;
	};

	bool HandlePull( Message m )
	{
		return true;
	}

};





